package com.example.demo.support;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ResourceUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @author Kevin
 * @date 2020/4/20 20:52
 */
@Slf4j
public class MyFileUtil {

    public static void downloadHelper(String fileName, HttpServletResponse response) throws FileNotFoundException, UnsupportedEncodingException {
        //设置下载响应头
        response.setHeader("content-disposition","attachment;fileName"+ URLEncoder.encode("/static/upload_file/"+fileName,"UTF-8"));
        //获取文件路径
        String uploadPath = ResourceUtils.getFile("classpath:").getAbsolutePath();
        File file = new File(uploadPath,"static/upload_file/"+fileName);

        if(file.exists()){ //判断文件父目录是否存在
            //response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            // response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment;fileName=" +   java.net.URLEncoder.encode(fileName,"UTF-8"));
            byte[] buffer = new byte[1024];
            FileInputStream fis = null; //文件输入流
            BufferedInputStream bis = null;

            OutputStream os = null; //输出流
            try {
                os = response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while(i != -1){
                    os.write(buffer);
                    i = bis.read(buffer);
                }

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            log.info("----------file download---" + fileName);
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
